package com.jinjiafeng.framelibrary.http;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.jinjiafeng.baselibrary.http.HttpUtils;
import com.jinjiafeng.baselibrary.http.ICallback;
import com.jinjiafeng.baselibrary.http.IHttpEngine;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.List;
import java.util.WeakHashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * date:on 18-4-23
 *
 * @author jinjiafeng
 */

public class OkHttpEngine implements IHttpEngine {
    private static final Handler HANDLER = new Handler();
    private static final OkHttpClient CLIENT = new OkHttpClient();
    private static final String TAG = "OkHttpEngine";

    @Override
    public void get(final boolean cache, Context context, String url, WeakHashMap<String, Object>
            params, final ICallback callback) {
        url = HttpUtils.jointParams(url, params);

        String cacheData = null;
        if (cache) {
            cacheData = CacheDataUtil.getCacheData(url);
            if (TextUtils.isEmpty(cacheData)) {
                callback.onSuccess(cacheData);
            }
        }

        final Request request = new Request.Builder()
                //请求接口。如果需要传参拼接到接口后面。
                .tag(context)
                .url(url)
                .build();
        final String finalCacheData = cacheData;
        final String finalUrl = url;
        CLIENT.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull final IOException e) {
                executeError(e, callback);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws
                    IOException {
                final ResponseBody body = response.body();
                if (body != null) {
                    final String result = body.string();
                    if (cache) {
                        if (result.equals(finalCacheData)) {
                            Log.d(TAG, "来自缓存: " + finalCacheData);
                            return;
                        }
                    }
                    Log.e("Get返回结果：", result);
                    //回调结果
                    executeSuccess(result, callback);
                    //缓存到数据库中
                    if (cache) {
                        CacheDataUtil.cacheData(finalUrl, result);
                    }
                }
            }
        });
    }

    private void executeError(@NonNull final Exception e, final ICallback callback) {
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                callback.onError(e);
            }
        });
    }

    private void executeSuccess(final String result, final ICallback callback) {
        try {
            HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    callback.onSuccess(result);
                }
            });
        } catch (Exception e) {
            executeError(e, callback);
            e.printStackTrace();
        }
    }

    @Override
    public void post(boolean cache, Context context, String url, WeakHashMap<String, Object> params,
                     final
                     ICallback callback) {
        RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder()
                .url(url)
                .tag(context)
                .post(requestBody)
                .build();

        CLIENT.newCall(request).enqueue(
                new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull final IOException e) {
                        executeError(e, callback);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws
                            IOException {
                        String resultJson = response.body().string();
                        executeSuccess(resultJson, callback);
                        // 缓存处理，下一期我们没事干，自己手写数据库框架
                    }
                }
        );
    }

    private RequestBody appendBody(WeakHashMap<String, Object> params) {
        final MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody
                .FORM);
        addParams(builder, params);
        return builder.build();
    }

    private void addParams(MultipartBody.Builder builder, WeakHashMap<String, Object> params) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.addFormDataPart(key, params.get(key) + "");
                final Object value = params.get(key);
                if (value instanceof File) {
                    File file = (File) value;
                    final String type = guessMediaType(file.getAbsolutePath());
                    builder.addFormDataPart(key, file.getName(),
                            RequestBody.create(MediaType.parse(type), file));
                } else if (value instanceof List) {
                    try {
                        @SuppressWarnings("unchecked") final List<File> fileList = (List<File>)
                                value;
                        for (int i = 0; i < fileList.size(); i++) {
                            final File file = fileList.get(i);
                            builder.addFormDataPart(key + i, file.getName(),
                                    RequestBody.create(MediaType.parse(guessMediaType(file
                                            .getAbsolutePath())), file));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    builder.addFormDataPart(key, value + "");
                }
            }

        }
    }

    private String guessMediaType(String path) {
        final FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }
}
